package com.liziyi0914.morearmor;

import com.google.common.collect.LinkedHashMultimap;
import com.google.common.collect.Multimap;
import com.liziyi0914.morearmor.effect.AbstractEffect;
import com.liziyi0914.morearmor.event.IListener;
import com.liziyi0914.morearmor.event.Listener;
import com.liziyi0914.morearmor.event.entity.WorldTickEvent;
import net.minecraft.entity.Entity;
import net.minecraft.entity.LivingEntity;
import net.minecraft.entity.effect.StatusEffect;
import net.minecraft.entity.effect.StatusEffectInstance;
import net.minecraft.server.network.ServerPlayerEntity;

import java.util.*;

public class StatusEffectManager implements IListener {

    private static final HashMap<AbstractEffect, HashSet<UUID>> recordMap = new HashMap<>();
    private static final Multimap<AbstractEffect, StatusEffect> effectMap = LinkedHashMultimap.create();

    @Listener
    public void onTick(WorldTickEvent e) {
        for (Entity entity : e.getWorld().getEntities()) {
            if (entity instanceof LivingEntity en) {
                UUID uuid = en.getUuid();
                final ServerPlayerEntity livingEntity = PlayerManager.get(uuid);
                if (livingEntity == null) continue;
                for (Map.Entry<AbstractEffect, Collection<StatusEffect>> entry : effectMap.asMap().entrySet()) {
                    final AbstractEffect effect = entry.getKey();
                    Collection<StatusEffect> statusEffects = entry.getValue();
                    if (!effect.predicateArmor().test(livingEntity)) {
                        if (recordMap.get(effect).contains(uuid)) {
                            statusEffects.stream().filter(livingEntity::hasStatusEffect).forEach(livingEntity::removeStatusEffect);
                            recordMap.get(effect).remove(uuid);
                        }
                    } else {
                        statusEffects.forEach(statusEffect -> livingEntity.setStatusEffect(new StatusEffectInstance(statusEffect, 20 * 3, 0), null));
                        recordMap.get(effect).add(uuid);
                    }
                }
            }
        }
    }

    public static void registerEffect(AbstractEffect effect, StatusEffect... statusEffect) {
        recordMap.put(effect, new HashSet<>());
        effectMap.removeAll(effect);
        effectMap.putAll(effect, Arrays.asList(statusEffect));
    }
}
